package cn.jiedh.app.meiweidk.web;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.tencent.smtt.sdk.WebView;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.base.BaseFragment;

/**
 * @name：
 * @author： liuyun
 * @phone： 15723310658
 * @createTime： 2017/12/12
 * @modifyTime： 2017/12/12
 * @explain：说明
 */


public class WebFragment extends BaseFragment implements WebErrorView.WebErrorViewClickListener,View.OnClickListener{
    public static final String EXTRA_TITLE = "extra.title";
    public static final String EXTRA_URL = "extra.url";
    public static final String EXTRA_CACHE_MODE = "extra.cache_mode";
    public static final String EXTRA_WEB_TITLE = "extra.web_title";

    String CUSTOM = "custom_scheme";

    public static final String TAG = "BaseWebViewFragment";

    public static final String TELEPHONY = "tel:";
    public static final String HTTP = "http:";
    public static final String HTTPS = "https:";
    public static final String NATIVE = "mxk" + ":";

    protected CommonWebView mWebView;
    protected WebErrorView mErrorView;
    protected AutoStepProgressBar mProgressBar;
    protected FrameLayout mRootView;

    protected boolean mIsWebViewAvailable;
    protected boolean mDestroyWebView = true;

    protected String mOriginUrl;
    protected String title;
    private boolean isUseWebViewTitle=true;

    protected View mTitleBarBack;
    protected View mTitleBarClose;
    protected TextView mTitleView;
    private View mView;
//    public static void launch(String url, String title, Context context) {
//
//        Intent intent=new Intent(context,WebActivity.class);
//        intent.putExtra(EXTRA_URL, url);
//        if (!TextUtils.isEmpty(title)) {
//            intent.putExtra(EXTRA_WEB_TITLE, title);
//        }
//        context.startActivity(intent);
//    }
//    public static void launch(String url, String title, int cacheMode, Context context) {
//        Intent intent=new Intent(context,WebActivity.class);
//        intent.putExtra(EXTRA_URL, url);
//        if (!TextUtils.isEmpty(title)) {
//            intent.putExtra(EXTRA_WEB_TITLE, title);
//        }
//        intent.putExtra(EXTRA_CACHE_MODE,cacheMode);
//        context.startActivity(intent);
//
//    }
    @Override
    protected int getLayoutView() {
        return R.layout.fragment_webview;
    }

    @Override
    protected void initView(View view) {
        mView=view;
        initTitleBar();

    }
    public void refreshCookie(Context context) {

    }
    protected void initTitleBar() {
        mTitleView=mView.findViewById(R.id.bar_tv_title);
        mTitleBarBack=mView.findViewById(R.id.bar_img_back);
        mTitleBarClose=mView.findViewById(R.id.bar_tv_close);
        mTitleBarClose.setVisibility(View.INVISIBLE);
        if(!TextUtils.isEmpty(title)){
            mTitleView.setText(title);
        }
        mTitleBarBack.setOnClickListener(this);
        mTitleBarClose.setOnClickListener(this);
    }
    protected void settingWebView(CommonWebView webView) {

    }
    @Override
    protected void initData() {

    }

        @Override
        public void onRefreshClicked() {

        }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case LoginWVJBHandler.REQUEST_CODE_LOGIN:
//                    refreshCookie(getContext());
//                    mWebView.refresh();
//                    break;
//            }
//        }
    }
    @Override
    public void onPause() {
        super.onPause();
        if(mWebView!=null)
        mWebView.safeOnPause();
    }
    @Override
    public void onResume() {
        if(mWebView!=null)
        mWebView.safeOnResume();
        super.onResume();
    }
    @Override
    public void onDestroy() {
        mIsWebViewAvailable = false;
        if (mDestroyWebView) {
            if (mWebView != null) {
                mWebView.destroy();
                mWebView = null;
            }
        } else {
            setWebView(null);
        }
        super.onDestroy();
    }
    public WebView getWebView() {
        return mIsWebViewAvailable ? mWebView : null;
    }
    public void setWebView(CommonWebView webView) {
        if (mWebView == webView) {
            return;
        }
        FrameLayout.LayoutParams params = null;
        if (mWebView != null) {
            mWebView.onPause();
            params = (FrameLayout.LayoutParams) mWebView.getLayoutParams();
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.setErrorView(null);
            mWebView.setLoading(null);
        }
        mWebView = webView;
        if (mWebView != null) {
            mWebView.onResume();
            if (params == null) {
                params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
            }
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mRootView.addView(mWebView, 0, params);
            mWebView.setErrorView(mErrorView);
            mWebView.setLoading(mProgressBar);
        }
    }
    public void setDestroyWebView(boolean destroyWebView) {
        mDestroyWebView = destroyWebView;
    }
    private class MyWebViewClient extends DefaultWebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            onWebPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
                view.loadUrl(url);
            } else if (url.startsWith(TELEPHONY)) {
                try {
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else if (url.startsWith(NATIVE)) {
//                Uri uri = Uri.parse(url);
//                Bundle bundle = new Bundle();
//                if (uri.isHierarchical()) {
//                    Set<String> names = uri.getQueryParameterNames();
//                    for (String name : names) {
//                        bundle.putString(name, uri.getQueryParameter(name));
//                    }
//                }
//                bundle.putBoolean(CUSTOM, true);
//                String host = uri.getHost();
//                String query = uri.getQuery();
//                uri = UriManager.getPageUri(host);
//                UriBuilder builder = UriBuilder.newInstance(uri);
//                builder.appendQueryString(query);
//                uri = builder.build();
//
//                LauncherActivity.openURL(uri, bundle, getActivity().getIntent(), getActivity());
            }
            return true;
        }
    }
    public void setUseWebViewTitle(boolean useWebViewTitle){
        isUseWebViewTitle=useWebViewTitle;
    }
    protected void onWebPageFinished(WebView view, String url) {
        updateLeftBar();
        if (TextUtils.isEmpty(title) && isUseWebViewTitle) {
            System.out.println(view.getTitle());
            mTitleView.setText(view.getTitle());

        }
    }
    @Override
    public void onClick(View v) {
        if (v == mTitleBarBack) {
            if (mWebView!=null && mWebView.canGoBack()) {
                mWebView.goBack();
            } else {
                getActivity().finish();
            }
        }
        else if (v == mTitleBarClose) {
            getActivity().finish();
        }
    }
    private void updateLeftBar() {
        if (mWebView.canGoBack()) {
            mTitleBarClose.setVisibility(View.VISIBLE);
        } else {
            mTitleBarClose.setVisibility(View.INVISIBLE);
        }
    }

    private boolean isVisible;
    private boolean isFirstVisible=true;
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            System.out.println("执行一次>>>>>>>>>>>>>>>>>");
            isVisible = true;
            loadWebViewisible();
        } else {
            isVisible = false;
        }
        System.out.println("setUserVisibleHint********************>>>>"+isVisible);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isVisible = true;
            loadWebViewisible();
        } else {
            isVisible = false;
        }
        System.out.println("onHiddenChanged********************>>>>"+isVisible);
    }
    private void loadWebViewisible(){
        if(isFirstVisible && mView instanceof ViewGroup){
            isFirstVisible=false;
            ((ViewGroup)mView).addView(View.inflate(getActivity(),R.layout.webview_layout,null));
            refreshCookie(getActivity());
            if (mWebView != null) {
                mWebView.destroy();
            }
            mRootView = ((FrameLayout) mView.findViewById(R.id.root));
            //mWebView = (CommonWebView) view.findViewById(R.id.webview);
            // because CommonWebView will be used in multiple window mode, we use application context to avoid context leak
            mWebView = new CommonWebView(getActivity());
//        mWebView.setWebChromeClient(new MyWebChromeClient());
            mWebView.setId(R.id.webview);
            mRootView.addView(mWebView, 0, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));

            mIsWebViewAvailable = true;

            mErrorView = (WebErrorView) mRootView.findViewById(R.id.error);
            mWebView.setErrorView(mErrorView);
            mErrorView.setErrorViewClickListener(this);

            mProgressBar = (AutoStepProgressBar) mRootView.findViewById(R.id.progress_bar);
            mWebView.setLoading(mProgressBar);
            mWebView.setCustomWebViewClient(new MyWebViewClient());
            settingWebView(mWebView);
            Bundle arguments = getArguments();
            if (arguments != null) {
                mOriginUrl=arguments.getString(EXTRA_URL);
                title=arguments.getString(EXTRA_WEB_TITLE);
                if(arguments.getInt(EXTRA_CACHE_MODE,-1)!=-1){
                    mWebView.getSettings().setCacheMode(arguments.getInt(EXTRA_CACHE_MODE,-1));
                }

            }
            if (mOriginUrl != null) {
                mWebView.loadUrl(mOriginUrl);
            }
            initValues();
        }
    }
    public void initValues(){

    }
}
